package com.cwd.arm.inter.controller;


import com.alibaba.fastjson.JSONObject;
import com.cwd.arm.common.dto.session.UserDto;
import com.cwd.arm.common.enums.MsgTypeEnum;
import com.cwd.arm.common.util.SessionUtil;
import com.cwd.arm.domain.job.dto.MsgJobDto;
import com.cwd.arm.domain.service.msg.MsgAppService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * Created by yan on 21-11-7.
 */
@Slf4j
@RestController
@RequestMapping(value = "/test")
public class TestController {

    @Autowired
    private Map<String, MsgAppService> msgAppServiceMap;


    @Secured({"ROLE_ADMIN"})
    @GetMapping("/admin/hello")
    public String admin() {
        return "admin";
    }

    @GetMapping("/test/user")
    public String user() {
        UserDto vo = SessionUtil.getUser();
        System.out.println(vo.getAuthorities());
        return "user";
    }

    @GetMapping("/job/msg")
    public String msgJob() {
        log.debug("start:MsgJob----------------------->");
        String jobParameters = null;
        MsgJobDto msgJobDto = buildMsgJobDto(jobParameters);
        for (MsgTypeEnum msgTypeEnum : msgJobDto.getMsgTypeEnums()) {
            MsgAppService msgAppService = msgAppServiceMap.get(msgTypeEnum.getCode());
            doJob(msgAppService, msgJobDto);
        }
        return "success";
    }

    public void doJob(MsgAppService msgAppService, MsgJobDto msgJobDto) {
        if (msgJobDto.getNeedCancelMsg()) {
            msgAppService.cancelRateWarnMsg();
        }
        if (msgJobDto.getNeedAddMsg()) {
            msgAppService.addRateWarnMsg();
        }
        try {
            if(msgJobDto.getNeedSendMsg()){
                msgAppService.sendMsg();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private MsgJobDto buildMsgJobDto(String jobParameters) {
        MsgJobDto jobDto;
        if (jobParameters == null) {
            jobDto = new MsgJobDto();
        } else {
            jobDto = JSONObject.parseObject(jobParameters, MsgJobDto.class);
        }
        if (jobDto.getMsgTypeEnums() == null) {
            jobDto.setMsgTypeEnums(MsgTypeEnum.values());
        }
        return jobDto;
    }

}
